package com.springboot.demo.core.shiro;

import com.springboot.demo.config.ApplicationContextRegister;
import com.springboot.demo.dao.UserMapper;
import com.springboot.demo.domain.User;
import com.springboot.demo.domain.UserExample;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.*;

public class MyShiroRealm extends AuthorizingRealm {
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
        String userId = ShiroUtils.getUserId();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        /*MenuService menuService = ApplicationContextRegister.getBean(MenuService.class);
        Set<String> perms = menuService.listPerms(userId);
        info.setStringPermissions(perms);*/
        System.out.println("获取权限");
        //获取用户权限
        Set<String> permissionSet = new HashSet<String>();
        permissionSet.add("权限添加");
        permissionSet.add("权限删除");
        info.setStringPermissions(permissionSet);

        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();
        String password = new String((char[]) token.getCredentials());

        UserMapper userMapper = ApplicationContextRegister.getBean(UserMapper.class);
        // 查询用户信息
        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.or();
        criteria.andEmailEqualTo(username);
        List<User> users = userMapper.selectByExample(example);


        // 账号不存在
        if (users == null || users.size() == 0) {
            throw new UnknownAccountException("账号不存在");
        }
        User user = users.get(0);

        // 密码错误
        if (!password.equals(user.getPasswd())) {
            throw new IncorrectCredentialsException("账号或密码不正确");
        }

        // 账号锁定
        if (!"NORMAL".equals(user.getStatus())) {
            throw new LockedAccountException("账号已被锁定,请联系管理员");
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPasswd(), user.getNickname());
        return info;
    }
}
